package httpfs

import (
	"io/fs"
	"net/http"
	"strings"
)

//http file system
type HFS struct {
	fs   http.FileSystem
	opts HfsOptions
}

func NewHFS(fsys fs.FS, opt ...HfsOption) *HFS {
	opts := HfsOptions{
		pathPrefix: "",
		indexName:  "index.html",
	}
	for _, o := range opt {
		o(&opts)
	}

	hfs := &HFS{
		fs:   http.FS(fsys),
		opts: opts,
	}

	return hfs
}

func (h *HFS) Open(name string) (http.File, error) {

	if name == "/" {
		//name = "."
		name = h.opts.indexName
	} else {
		name = strings.TrimPrefix(name, "/")
	}

	newName := h.opts.pathPrefix + name
	//log.Println("HFS open", name, newName)
	return h.fs.Open(newName)
}
